package com.wuhongyu.service.impl;

import com.wuhongyu.base.BaseServiceImpl;
import com.wuhongyu.common.MyCommon;
import com.wuhongyu.entity.Customer;
import com.wuhongyu.entity.Runoff;
import com.wuhongyu.entity.User;
import com.wuhongyu.repository.RunoffDao;
import com.wuhongyu.base.BaseService;
import com.wuhongyu.service.RunoffService;
import com.wuhongyu.util.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("runoffService")
public class RunoffServiceImpl extends BaseServiceImpl<Runoff> implements RunoffService {


    private RunoffDao runoffDao;
    @Resource
    public void setDao(RunoffDao runoffDao){
        super.setBaseDao(runoffDao);
        this.runoffDao = runoffDao;
    }

    @Override
    public Page<Runoff> findAll(Runoff runoff, Integer number) {
        Specification<Runoff> spec = (root,query,cb) ->{
            //关联客户
            Join<Runoff, Customer> root1 = root.join("customer");
            //关联客户经理
            Join<Customer, User> root2 = root1.join("managerUser");
            List<Predicate> list = new ArrayList<>();
            if(runoff.getCustomer()!=null && MyUtil.notEmpty(runoff.getCustomer().getName()))
                list.add(cb.and(cb.like(root1.get("name"),"%"+runoff.getCustomer().getName()+"%")));
            if(runoff.getCustomer()!=null && runoff.getCustomer().getManagerUser()!=null && MyUtil.notEmpty(runoff.getCustomer().getManagerUser().getName()))
                list.add(cb.and(cb.like(root2.get("name"),"%"+runoff.getCustomer().getManagerUser().getName()+"%")));
            if(!StringUtils.isEmpty(runoff.getStatus()))
                list.add(cb.and(cb.equal(root.get("status"),runoff.getStatus())));
            return cb.and(list.toArray(new Predicate[list.size()]));
        };
        return runoffDao.findAll(spec, new PageRequest(MyUtil.getCurrentPage(number), MyCommon.PAGESIZE));

    }

    @Override
    public void save(Runoff runoff) {
        //暂缓流失
        if(runoff.getAction()!=null && runoff.getResult()==null){
            Runoff runoff1 = runoffDao.getOne(runoff.getId());
            runoff1.setAction(runoff.getAction());
            runoff1.setStatus(1);
            runoffDao.save(runoff1);
        }else {
            //确认流失
            Runoff runoff1 = runoffDao.getOne(runoff.getId());
            runoff1.setResult(runoff.getResult());
            runoff1.setStatus(2);
            runoff1.setLosttime(new Date());
            runoffDao.save(runoff1);
        }
    }

}